import request from "./request";
import { requestWithAuth } from "./request";
import { ElMessage } from "element-plus";
import { validateAdminData } from "@/utils/validators";
import cache from "@/utils/cache";

const CACHE_KEY = {
  ADMIN_LIST: "admin_list",
  ADMIN_DETAIL: "admin_detail_",
};

const CACHE_DURATION = 5 * 60 * 1000; // 5分钟缓存

/**
 * 统一的错误处理
 * @param {Error} error - 错误对象
 * @param {string} customMessage - 自定义错误消息
 */
const handleError = (error, customMessage = "操作失败") => {
  console.error(error);
  ElMessage.error(customMessage);
  throw error;
};

/**
 * 获取管理员列表
 * @param {Object} params - 查询参数
 * @returns {Promise} - 返回管理员列表数据
 */
export async function getAdmins(params = {}) {
  try {
    // 参数验证
    const defaultParams = {
      search: "",
      sortBy: "adminName",
      ascending: true,
      page: 1,
      pageSize: 10,
    };
    const queryParams = { ...defaultParams, ...params };

    // 检查缓存
    const cacheKey = `${CACHE_KEY.ADMIN_LIST}_${JSON.stringify(queryParams)}`;
    const cachedData = cache.get(cacheKey);
    if (cachedData) {
      return cachedData;
    }

    const response = await requestWithAuth({
      url: "/Admin/list",
      method: "get",
      params: queryParams,
    });

    // 设置缓存
    cache.set(cacheKey, response, CACHE_DURATION);
    return response;
  } catch (error) {
    handleError(error, "获取管理员列表失败");
  }
}

/**
 * 获取单个用户信息
 * @param {number} id - 管理员ID
 * @returns {Promise} - 返回管理员信息
 */
export async function getAdmin(id) {
  try {
    if (!id) throw new Error("管理员ID不能为空");

    // 检查缓存
    const cacheKey = `${CACHE_KEY.ADMIN_DETAIL}${id}`;
    const cachedData = cache.get(cacheKey);
    if (cachedData) {
      return cachedData;
    }

    const response = await request({
      url: `/Admin/detail/${id}`,
      method: "get",
    });

    cache.set(cacheKey, response, CACHE_DURATION);
    return response;
  } catch (error) {
    handleError(error, "获取管理员详情失败");
  }
}

/**
 * 批量删除管理员
 * @param {number[]} ids - 要删除的管理员ID数组
 * @returns {Promise} - 返回删除操作的结果
 */
export const batchDeleteAdmins = async (ids) => {
  try {
    if (!Array.isArray(ids) || ids.length === 0) {
      throw new Error("请选要删除的管理员");
    }

    const response = await request({
      url: "/Admin/batchDelete",
      method: "DELETE",
      data: { ids },
    });

    // 清除相关缓存
    cache.removeByPrefix(CACHE_KEY.ADMIN_LIST);
    ids.forEach((id) => cache.remove(`${CACHE_KEY.ADMIN_DETAIL}${id}`));

    return response;
  } catch (error) {
    handleError(error, "批量删除管理员失败");
  }
};

/**
 * 删除管理员
 * @param {number} id - 要删除的管理员ID
 * @returns {Promise} - 返回删除操作的结果
 */
export const deleteAdmin = async (id) => {
  try {
    if (!id) throw new Error("管理员ID不能为空");

    const response = await request({
      url: `/Admin/${id}`,
      method: "DELETE",
    });

    // 清除相关缓存
    cache.removeByPrefix(CACHE_KEY.ADMIN_LIST);
    cache.remove(`${CACHE_KEY.ADMIN_DETAIL}${id}`);

    return response;
  } catch (error) {
    handleError(error, "删除管理员失败");
  }
};

/**
 * 创建新管理员
 * @param {Object} adminData - 新管理员的数据
 * @returns {Promise} - 返回创建操作的结果
 */
export const createAdmin = async (adminData) => {
  try {
    // 数据验证
    const validationResult = validateAdminData(adminData);
    if (!validationResult.isValid) {
      throw new Error(validationResult.message);
    }

    const response = await request({
      url: "/Admin/create",
      method: "POST",
      data: adminData,
    });

    // 清除列表缓存
    cache.removeByPrefix(CACHE_KEY.ADMIN_LIST);

    return response;
  } catch (error) {
    handleError(error, "创建管理员失败");
  }
};

/**
 * 更新管理员信息
 * @param {Object} adminData - 更新的管理员数据
 * @returns {Promise} - 返回更新操作的结果
 */
export const updateAdmin = async (adminData) => {
  try {
    // 数据验证
    const validationResult = validateAdminData(adminData);
    if (!validationResult.isValid) {
      throw new Error(validationResult.message);
    }

    const response = await request({
      url: `/Admin/update/${adminData.adminId}`,
      method: "PUT",
      data: adminData,
    });

    // 清除相关缓存
    cache.removeByPrefix(CACHE_KEY.ADMIN_LIST);
    cache.remove(`${CACHE_KEY.ADMIN_DETAIL}${adminData.adminId}`);

    return response;
  } catch (error) {
    handleError(error, "更新管理员信息失败");
  }
};

/**
 * 批量导入管理员
 * @param {Array} admins - 管理员数据数组
 * @returns {Promise} - 返回导入操作的结果
 */
export const batchImportAdmins = async (admins) => {
  try {
    if (!Array.isArray(admins) || admins.length === 0) {
      throw new Error("导入数据不能为空");
    }

    // 验证管理员数据
    admins.forEach((admin, index) => {
      const validationResult = validateAdminData(admin);
      if (!validationResult.isValid) {
        throw new Error(
          `第${index + 1}条数据验证失败: ${validationResult.message}`
        );
      }
    });

    const response = await request({
      url: "/Admin/batchImport",
      method: "POST",
      data: { admins },
    });

    // 清除列表缓存
    cache.removeByPrefix(CACHE_KEY.ADMIN_LIST);

    return response;
  } catch (error) {
    handleError(error, "批量导入管理员失败");
  }
};

/**
 * 获取角色列表
 */
export async function getRoles() {
  try {
    const response = await requestWithAuth({
      url: "/Role/list",
      method: "get",
      // 添加防重复请求标识
      headers: {
        "Request-Type": "getRoles",
      },
    });
    //console.log("getRoles response:", response); // 添加调试日志
    return {
      data: response.data.data || [],
    };
  } catch (error) {
    // 如果是重复请求取消的错误，直接返回空数组
    if (error.message === "重复请求已取消") {
      return { data: [] };
    }
    throw error;
  }
}

/**
 * 获取管理员角色
 */
export async function getAdminRoles(adminId) {
  try {
    if (!adminId) {
      throw new Error("管理员ID不能为空");
    }

    const response = await requestWithAuth({
      url: `/Admin/roles`,
      method: "get",
      params: { adminId },
      // 添加防重复请求标识
      headers: {
        "Request-Type": `getAdminRoles_${adminId}`,
      },
    });

    //console.log("getAdminRoles response:", response); // 添加调试日志
    return response;
  } catch (error) {
    // 如果是重复请求取消的错误，直接返回空数组
    if (error.message === "重复请求已取消") {
      return { data: [] };
    }
    throw error;
  }
}

/**
 * 保存管理员角色
 * @param {number} adminId - 管理员ID
 * @param {number[]} roles - 角色ID数组
 * @returns {Promise} - 返回保存操作的结果
 */
export async function saveAdminRoles(adminId, roles) {
  if (!adminId) {
    return Promise.reject(new Error("管理员ID不能为空"));
  }
  if (!Array.isArray(roles) || roles.length === 0) {
    return Promise.reject(new Error("角色不能为空"));
  }

  // 根据 AssignRoleMode  l 的要求构造数据
  const response = await requestWithAuth({
    url: "/Admin/assignRole",
    method: "post",
    data: {
      adminId: adminId,
      roles: roles, // 直接传递角色ID数组
    },
  });

  return response;
}
